<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use DB;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class PersonageController extends Controller
{
    //个人中心页面
    public function getPersonage()
    {
        //从session中获取登陆用户的id
        $id = session('id');
        //根据id查询给用户的数据
        $users = DB::table('hs_member')->where('id',$id)->select()->first();
        // dd($users);
        $backs = DB::table('hs_back')->where('b_status',0)->first();
        //解析模板将数据分配给模板
        return view('home.personage.personage',['users'=>$users,'backs'=>$backs]);

    }

    //个人信息修改页面
    public function install()
    {
        $id = session('id');

        $users = DB::table('hs_member')->where('id',$id)->select()->first();

        $back = DB::table('hs_back')->select()->get();
        
        $backs = DB::table('hs_back')->where('b_status',0)->first();
        // dd($backs);
        return view('home.personage.install',['users'=>$users,'back'=>$back,'backs'=>$backs]);
    }

    //执行个人信息修改
    public function doinstall(Request $request)
    {
        // dd($request->all());
        $id = session('id');

        $users = DB::table('hs_member')->where('id',$id)->select()->first();


        //判断是否为空
        if(!empty($request->input('name'))){
            $data['name'] = $request -> input('name');
        }

        if(Hash::check($request->input('password'),$users->password)){
            if(!empty($request->input('repassword'))){
                $data['password'] = Hash::make($request -> input('repassword'));
            }
        }

        
        if(!empty($request->input('text'))){
            $data['sign'] = $request -> input('text');
        }

        if(!empty($request->input('pic'))){
            $data['pic'] = $request -> input('pic');
            $images=$request->file('pic'); //使用laravel 自带的request类来获取一下文件.

            $filedir="upload/home/Images"; //定义图片上传路径

            $imagesName=$images->getClientOriginalName(); //获取上传图片的文件名

            //如果需要重命名：
            $newImagesName=md5(time()).rand(10000,99999).".".$extension; //重新命名上传文件名字 

            $images->move($filedir,$newImagesName); //使用move 方法移动文件.
        }

        dd($data);
        if(!empty($data)){
            $update = DB::table('hs_member')->where('id',$id)->update($data);
            if($update){
                return redirect('/home/personage')->with('success','您的个人信息已经修改成功');
            }else{
                return redirect('/install')->with('error','您修改失败');
            }
        }else{
            return redirect('/home/personage')->with('error','您未进行修改');
        }


    }
}
